package rexsee.core.progress;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.style.RexseeDrawable;
import rexsee.core.style.StyleSheet;
import rexsee.core.widget.DivDialog;
import rexsee.core.widget.LabelDiv;
import rexsee.core.widget.ProgressDiv;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Chronometer;
import android.widget.LinearLayout;

public class RexseeProgressCover implements JavascriptInterface {

	public static final String INTERFACE_NAME = "ProgressCover";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return childBrowser.progressCover;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeProgressCover(childBrowser);
	}

	public static final String DATABASE_PROGRESSCOVER = "progressCover.db";
	public static final String TABLE_STYLE = "style";

	public static final String DefaultDialogBackground = "#222222+#444444+#AAAAAA+#222222";
	public static final String DefaultDialogStyle = "border-width:0px;alpha:1;width:fillparent;height:fillparent;top:0;left:0;window-cancelable:false;padding:0 0 75 0;background-color:transparent;align:center; vertical-align:bottom;window-animation:none;";
	public static final String DefaultLabelStyle = "width:wrapcontent;height:wrapcontent;label-width:wrapcontent;label-height:wrapcontent;font-size:14px;background-color:transparent;label-padding:1 3 1 3;label-background-color:#888888;color:#FFFFFF;icon-width:48;icon-height:48;border-width:0;";
	public static final String DefaultProgressStyle = "margin:5px;width:200px;height:16px;border-color:#111111 #eeeeee #eeeeee #111111;border-width:1px;";
	public static final String DefaultChronometerStyle = "width:wrapcontent;height:wrapcontent;font-size:14px;label-padding:1 3 1 3;border-width:0px;background-color:#888888;color:#FFFFFF;label:0;icon-visibility:hidden;";

	private final Context mContext;
	private final Browser mBrowser;

	private DivDialog mCoverProgressDialog = null;
	private LabelDiv label;
	private ProgressDiv progress;
	private Chronometer mMeter;

	public RexseeProgressCover(Browser browser) {
		super();
		mBrowser = browser;
		mContext = browser.getContext();
	}

	public Drawable getDefaultBackground() {
		return (mBrowser.application.resources.cover == null) ? RexseeDrawable.getDrawable(mBrowser, DefaultDialogBackground) : mBrowser.application.resources.cover;
	}

	public void showWithRunnable(final int progressInt, final String progressText, final int timeout, final Runnable timeoutRunnable, final Runnable cancelRunnable) {
		((Activity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {

				if (mCoverProgressDialog == null) {

					String labelStyle = DefaultLabelStyle + getLabelStyle() + "label:" + progressText + ";";
					String progressStyle = DefaultProgressStyle + getProgressStyle() + "progress:" + progressInt + ";";
					String chronometerStyle = DefaultChronometerStyle + getChronometerStyle();
					String dialogStyle = DefaultDialogStyle + getDialogStyle() + "window-auto-hide:" + timeout + ";";
					StyleSheet dialogStyleSheet = new StyleSheet(mContext).parseStyle(dialogStyle);

					label = new LabelDiv(mContext);
					label.styleSheet.icon = mBrowser.application.icon;
					label.setStyle(labelStyle);

					progress = new ProgressDiv(mContext);
					progress.setStyle(progressStyle);

					final LabelDiv chronometer = new LabelDiv(mContext);
					chronometer.setStyle(chronometerStyle);

					LinearLayout mCover = new LinearLayout(mContext);
					mCover.setOrientation(LinearLayout.VERTICAL);
					mCover.addView(label);
					mCover.addView(progress);
					mCover.addView(chronometer);
					mCover.setGravity(dialogStyleSheet.getGravity());

					mCoverProgressDialog = new DivDialog(mBrowser, null, dialogStyle);
					if (dialogStyleSheet.background_color.equals("transparent")) {
						mCoverProgressDialog.div.innerLayout.setBackgroundDrawable(getDefaultBackground());
					}
					mCoverProgressDialog.setOnKeyListener(new Dialog.OnKeyListener() {
						@Override
						public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
							if (arg1 == KeyEvent.KEYCODE_SEARCH) return true;
							else if (arg1 == KeyEvent.KEYCODE_BACK) {
								if (cancelRunnable != null) cancelRunnable.run();
								return true;
							} else return false;
						}
					});
					mCoverProgressDialog.addChild(mCover);
					mMeter = new Chronometer(mContext);
					mMeter.setVisibility(View.GONE);
					mMeter.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
						@Override
						public void onChronometerTick(Chronometer c) {
							int elapsedTime = string2second(c.getText().toString());
							if (timeout > 0 && elapsedTime >= timeout) {
								if (timeoutRunnable != null) timeoutRunnable.run();
							} else {
								chronometer.setStyle("label:" + elapsedTime + ";");
							}
						}
					});
					mCoverProgressDialog.addChild(mMeter);
					mCoverProgressDialog.start();
					mMeter.start();

				} else {

					progress.setStyle("progress:" + progressInt + ";");
					label.setStyle("label:" + progressText + ";");

				}
			}
		});
	}
	public static final String second2string(int second) {
		int h = Math.round(second / 3600);
		int m = Math.round((second % 3600) / 60);
		int s = (second % 3600) % 60;
		return h + ":" + m + ":" + s;
	}
	public static final int string2second(String string) {
		try {
			String[] s = string.split(":");
			if (s.length >= 3) {
				return Integer.parseInt(s[0].trim()) * 3600 + Integer.parseInt(s[1].trim()) * 60 + Integer.parseInt(s[2].trim());
			} else if (s.length == 2) {
				return Integer.parseInt(s[0].trim()) * 60 + Integer.parseInt(s[1].trim());
			} else {
				return Integer.parseInt(s[0].trim());
			}
		} catch (Exception e) {
			return -1;
		}
	}

	//JavaScript Interface

	public void show(final int progressInt, final String progressText, final int timeout, final String timeoutCallback, final String cancelCallback) {
		Runnable timeoutRunnable = (timeoutCallback == null || timeoutCallback.equals("")) ? null : new Runnable() {
			@Override
			public void run() {
				try {
					if (mBrowser != null) mBrowser.function.load(timeoutCallback);
				} catch (Exception e) {
				}
			}
		};
		Runnable cancelRunnable = (cancelCallback == null || cancelCallback.equals("")) ? null : new Runnable() {
			@Override
			public void run() {
				try {
					if (mBrowser != null) mBrowser.function.load(cancelCallback);
				} catch (Exception e) {
				}
			}
		};
		showWithRunnable(progressInt, progressText, timeout, timeoutRunnable, cancelRunnable);
	}
	public void show(int progressInt, String progressText, String cancelCallback) {
		show(progressInt, progressText, -1, null, cancelCallback);
	}
	public void show(int progressInt, String progressText) {
		show(progressInt, progressText, -1, null, null);
	}

	public void hide() {
		((Activity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					if (mCoverProgressDialog != null) {
						mCoverProgressDialog.dismiss();
						mCoverProgressDialog = null;
						label = null;
						progress = null;
					}
				} catch (Exception e) {
				}
			}
		});
	}

	public void setStyle(String dialogStyle, String labelStyle, String progressStyle, String chronometerStyle) {
		try {
			SQLiteDatabase db = mContext.openOrCreateDatabase(DATABASE_PROGRESSCOVER, Context.MODE_PRIVATE, null);
			db.execSQL("CREATE TABLE if not exists " + TABLE_STYLE + " (dialogStyle TEXT,labelStyle TEXT,progressStyle TEXT,chronometerStyle TEXT);");
			db.execSQL("DELETE FROM " + TABLE_STYLE + ";");
			db.execSQL("INSERT INTO " + TABLE_STYLE + " VALUES ('" + dialogStyle + "','" + labelStyle + "','" + progressStyle + "','" + chronometerStyle + "');");
			db.close();
		} catch (Exception e) {
		}
	}
	public String getDialogStyle() {
		SQLiteDatabase db = null;
		try {
			db = mContext.openOrCreateDatabase(DATABASE_PROGRESSCOVER, Context.MODE_PRIVATE, null);
		} catch (Exception e) {
		}
		if (db == null) return "";
		try {
			db.execSQL("CREATE TABLE if not exists " + TABLE_STYLE + " (dialogStyle TEXT,labelStyle TEXT,progressStyle TEXT,chronometerStyle TEXT);");
			Cursor cursor = db.rawQuery("SELECT * from " + TABLE_STYLE + ";", null);
			if (cursor == null || cursor.getCount() == 0) {
				try {
					cursor.close();
				} catch (Exception e) {
				}
				db.close();
				return "";
			} else {
				cursor.moveToFirst();
				String rtn = cursor.getString(0);
				cursor.close();
				db.close();
				return rtn;
			}
		} catch (Exception e) {
			db.close();
			return "";
		}
	}
	public String getLabelStyle() {
		SQLiteDatabase db = null;
		try {
			db = mContext.openOrCreateDatabase(DATABASE_PROGRESSCOVER, Context.MODE_PRIVATE, null);
		} catch (Exception e) {
		}
		if (db == null) return "";
		try {
			db.execSQL("CREATE TABLE if not exists " + TABLE_STYLE + " (dialogStyle TEXT,labelStyle TEXT,progressStyle TEXT,chronometerStyle TEXT);");
			Cursor cursor = db.rawQuery("SELECT * from " + TABLE_STYLE + ";", null);
			if (cursor == null || cursor.getCount() == 0) {
				try {
					cursor.close();
				} catch (Exception e) {
				}
				db.close();
				return "";
			} else {
				cursor.moveToFirst();
				String rtn = cursor.getString(1);
				cursor.close();
				db.close();
				return rtn;
			}
		} catch (Exception e) {
			db.close();
			return "";
		}
	}
	public String getProgressStyle() {
		SQLiteDatabase db = null;
		try {
			db = mContext.openOrCreateDatabase(DATABASE_PROGRESSCOVER, Context.MODE_PRIVATE, null);
		} catch (Exception e) {
		}
		if (db == null) return "";
		try {
			db.execSQL("CREATE TABLE if not exists " + TABLE_STYLE + " (dialogStyle TEXT,labelStyle TEXT,progressStyle TEXT,chronometerStyle TEXT);");
			Cursor cursor = db.rawQuery("SELECT * from " + TABLE_STYLE + ";", null);
			if (cursor == null || cursor.getCount() == 0) {
				try {
					cursor.close();
				} catch (Exception e) {
				}
				db.close();
				return "";
			} else {
				cursor.moveToFirst();
				String rtn = cursor.getString(2);
				cursor.close();
				db.close();
				return rtn;
			}
		} catch (Exception e) {
			db.close();
			return "";
		}
	}
	public String getChronometerStyle() {
		SQLiteDatabase db = null;
		try {
			db = mContext.openOrCreateDatabase(DATABASE_PROGRESSCOVER, Context.MODE_PRIVATE, null);
		} catch (Exception e) {
		}
		if (db == null) return "";
		try {
			db.execSQL("CREATE TABLE if not exists " + TABLE_STYLE + " (dialogStyle TEXT,labelStyle TEXT,progressStyle TEXT,chronometerStyle TEXT);");
			Cursor cursor = db.rawQuery("SELECT * from " + TABLE_STYLE + ";", null);
			if (cursor == null || cursor.getCount() == 0) {
				try {
					cursor.close();
				} catch (Exception e) {
				}
				db.close();
				return "";
			} else {
				cursor.moveToFirst();
				String rtn = cursor.getString(3);
				cursor.close();
				db.close();
				return rtn;
			}
		} catch (Exception e) {
			db.close();
			return "";
		}
	}

}
